package com.jike.noobmoney.mvp.view.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jike.noobmoney.R;
import com.jike.noobmoney.entity.RegistEntity;
import com.jike.noobmoney.entity.SmsEntity;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.util.PerfectClickListener;
import com.jike.noobmoney.util.RegexUtils;
import com.jike.noobmoney.util.ToastUtils;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.cb_pwd)
    CheckBox cbPwd;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_check_code)
    Button btnCheckCode;
    @BindView(R.id.et_commend_code)
    EditText etCommendCode;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.ll_register)
    LinearLayout llRegister;

    private boolean timeEnable = true;
    private Call<SmsEntity> codeCall;
    private String smscode = "";
    private Call<RegistEntity> registCall;

    @Override
    protected int layoutResID() {
        return R.layout.activity_register;
    }

    @Override
    protected void initData() {
        setListener();
    }

    /**
     * 设置监听
     */
    private void setListener() {
        //手机号
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (timeEnable) {
                    boolean enable = !TextUtils.isEmpty(s);
                    btnCheckCode.setEnabled(enable);
                }
            }
        });

        cbPwd.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
                etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                etPassword.setSelection(etPassword.getText().length());
            } else {
                etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                etPassword.setSelection(etPassword.getText().length());
            }
        });

        btnCheckCode.setOnClickListener(listener);
        tvRegister.setOnClickListener(listener);
    }


    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_check_code) {
                if (isVerPhone()) {
                    timeEnable = false;
                    btnCheckCode.setEnabled(false);
                    CountDownTimer mCountDownTimer = new CountDownTimer(
                            60 * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            long s = millisUntilFinished / 1000;
                            String text = s + "s";
                            btnCheckCode.setText(text);
                        }

                        @Override
                        public void onFinish() {
                            timeEnable = true;
                            btnCheckCode.setText("发送验证码");
                            boolean enable = !TextUtils.isEmpty(etPhone.getText().toString());
                            btnCheckCode.setEnabled(enable);
                            this.cancel();
                        }
                    };
                    mCountDownTimer.start();
                    //发短信
                    getMessage();
                }
            } else if (id == R.id.tv_register) {
                //检查是否可以注册
                if (isPrepared()) {
                    //检查完毕，开始注册
                    regist();
                }
            }
        }

    };

    /**
     * 发送短信验证码
     */
    private void getMessage() {
        codeCall = RetrofitHelper.getInstance().getCode(etPhone.getText().toString().trim());
        codeCall.enqueue(new Callback<SmsEntity>() {
            @Override
            public void onResponse(Call<SmsEntity> call, Response<SmsEntity> response) {
                if (response != null) {
                    SmsEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            //成功
//                            ToastUtils.showShortToastSafe(body.getRinfo());
//                            smscode = body.getSmscode();
//                            Log.e("xuke", "smsCode=" + smscode);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<SmsEntity> call, Throwable t) {
                Log.e("xuke", t.getMessage());
            }
        });

    }

    /**
     * 注册
     */
    private void regist() {
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String commentCode = etCommendCode.getText().toString().trim();
        String etCodeStr      =etCode.getText().toString().trim();
        registCall = RetrofitHelper.getInstance().regist(phone, password,etCodeStr, commentCode);
        registCall.enqueue(new Callback<RegistEntity>() {
            @Override
            public void onResponse(Call<RegistEntity> call, Response<RegistEntity> response) {
                if (response != null) {
                    RegistEntity body = response.body();
                    if (body != null) {
                        if ("100".equals(body.getCode())) {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showShortToastSafe(body.getRinfo());
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<RegistEntity> call, Throwable t) {
                Log.e("xuke", t.getMessage());
            }
        });

    }


    //检查手机号
    private boolean isVerPhone() {
        if (!RegexUtils.checkMobileNumber(etPhone.getText().toString())) {
            ToastUtils.showShortToastSafe("请检查手机号的格式");
            etPhone.requestFocus();
            return false;
        }
        return true;
    }

    private boolean isPrepared() {
        if (!RegexUtils.checkMobileNumber(etPhone.getText().toString())) {
            ToastUtils.showShortToastSafe("请输入正确的手机号");
            etPhone.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(etCode.getText().toString())) {
            ToastUtils.showShortToastSafe("请输入验证码");
            etCode.requestFocus();
            return false;
        }

//        String trim = etCode.getText().toString().trim();
//        if (!trim.equals(smscode)) {
//            ToastUtils.showShortToastSafe("验证码不正确");
//            etCode.requestFocus();
//            return false;
//        }
        if (!RegexUtils.passwordCheck(etPassword.getText().toString())) {
            ToastUtils.showShortToastSafe("请输入6或6位以上密码");
            etPassword.requestFocus();
            return false;
        }
        return true;
    }


}


